﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Reflection;

namespace Xman.Extensions.Core
{
    public static class CollectionExtensions
    {
        /// <summary>
        ///from ICollection<T> to string
        /// </summary>
        /// <param name="list"></param>
        /// <returns></returns>
        public static string ToStringJoin<T>(this ICollection<T> list, string joinnode = ",")
        {
            return string.Join(joinnode, list.ToArray());
        }

        /// <summary>
        /// 转换成string 用于数据库in查询  形似("1","2")
        /// </summary>
        /// <param name="list"></param>
        /// <returns></returns>
        public static string ToSqlIn<T>(this ICollection<T> list)
        {
            var value = list.Count > 0 ? "'" + list.ToStringJoin(",").Replace(",", "','") + "'" : "";
            return value;
        }

        /// <summary>
        /// Checks whatever given collection object is null or has no item.
        /// </summary>
        public static bool IsNullOrEmpty<T>(this ICollection<T> source)
        {
            return source is not {Count: > 0};
        }


        /// <summary>
        /// Collection 是否为空
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="source"></param>
        /// <param name="count"></param>
        /// <returns></returns>
        public static bool IsMoreThanCount<T>(this ICollection<T> source,int count=1)
        {
            return !source.IsNullOrEmpty() && source.Count > count;
        }

        /// <summary>
        /// 转为可空的List
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="source"></param>
        /// <returns></returns>
        public static XList<T> ToXList<T>(this IEnumerable<T> source)
        {
            return source == null ? new XList<T>() : new XList<T>(source);
        }

        /// <summary>  
        /// 转化一个DataTable  
        /// </summary>  
        /// <typeparam name="T"></typeparam>  
        /// <param name="list"></param>  
        /// <returns></returns>  
        public static DataTable ToDataTable<T>(this IEnumerable<T> list)
        {

            //创建属性的集合  
            var pList = new List<PropertyInfo>();
            //获得反射的入口  

            var type = typeof(T);
            var dt = new DataTable();
            //把所有的public属性加入到集合 并添加DataTable的列  
            Array.ForEach(type.GetProperties(), p =>
            {
                pList.Add(p);
                dt.Columns.Add(p.Name, p.PropertyType);
            });
            foreach (var item in list)
            {
                //创建一个DataRow实例  
                var row = dt.NewRow();
                //给row 赋值  
                pList.ForEach(p => row[p.Name] = p.GetValue(item, null)!);
                //加入到DataTable  
                dt.Rows.Add(row);
            }
            return dt;
        }
    }
}
